import Utils from "../../Utils";
import DestructibleFacility from "../facility/DestructibleFacility";
import LaunchableFalicity from "../facility/LaunchableFalicity";
import Flare from "../flyer/DestructibleFlyer/FlyerMissile/Flare";
import Launchable from "../funcObj/interface/Launchable";
import { FacilityType } from "../info/GameEnum";
import { Global } from "../info/Global";
import { Location } from "../info/Predefine";
import GameManager from "../manager/GameManager";
import NodePoolManager from "../manager/NodePoolManager";
import Player from "../player/Player";

const { ccclass, property } = cc._decorator;

/**
 * 回收
 */
@ccclass
export default class FlareReserve extends LaunchableFalicity {
    creat(): void { }

    fac: DestructibleFacility = null;

    flareCount: number;

    get count(): number {
        return this.flareCount;
    }

    get locations(): Location[] {
        return this.fac.locations;
    }

    init(player: Player, fac: DestructibleFacility): void {
        this.player = player;
        this.facilityInfo = Global.getFacilityInfo<any>(FacilityType.照明弹基地);
        this.fac = fac;
        this.flareCount = 5;
        this.fac.node.on(DestructibleFacility.EventType.摧毁, this.die, this);
        
        this.dispatchQueue = [];
        this.dispatching = false;
    }

    dispatch(target: Location) {
        this.flareCount--;
        this.fac.player.node.emit(Player.EventType.更新飞行物数量, FacilityType.照明弹基地, -1);
        let flyerParent = this.fac.player.flyerParentNode;
        let flareBullet = NodePoolManager.instance.obtain(NodePoolManager.instance.flareBullet);

        this.dispatchQueue.push({
            target: target, flyer: flareBullet, dispatchFunc: () => {
                flareBullet.parent = flyerParent;
                flareBullet.position = flyerParent.convertToNodeSpaceAR(this.node.convertToWorldSpaceAR(cc.Vec3.ZERO));
                let targetPositon = GameManager.instance.getGamePosition(target);
                targetPositon.x = Utils.getRandom(targetPositon.x - 39, targetPositon.x + 39);
                targetPositon.y = Utils.getRandom(targetPositon.y - 39, targetPositon.y + 39);
                flareBullet.getComponent(Flare).init(this.fac, targetPositon);
            }
        })
    }

    /**
     * 如果没有了并且全部发射结束了
     */
    protected autoDispatch(): void {
        super.autoDispatch();
        if (this.count == 0 && this.dispatchQueue.length == 0)
            this.die();
    }


    die() {
        this.dispatching = false;
        this.dispatchQueue = [];
        this.fac.node.targetOff(this);
        NodePoolManager.instance.recycle(this.node);
        this.flareCount = 0;
        this.fac = null;
    }
}